<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
    />
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadMarkDownImg } from '@/api/manage'
import {mapGetters} from "vuex";

export default {
  name: 'MyEditor',
  components: {
    Editor, Toolbar
  },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            maxFileSize: 1 * 1024 * 1024, // 1M
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 3,
            customUpload:    //自定义上-oss
              async(file, insertFn) => {
                await this.ossUpload(file, insertFn)
              }
          },
          uploadVideo: {
            maxFileSize: 1 * 1024 * 1024, // 1M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 3,
            customUpload:    //自定义上-oss
              async(file, insertFn) => {
                await this.ossUpload(file, insertFn)
              }
          }
        }
      },
      mode: 'default', // or 'simple',
      url: {
        upload: '/sys/common/articleUpload'
      }
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  mounted() {
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    ossUpload(file, insertFn) {
      const formdata = new FormData()
      formdata.append('file', file)
      formdata.append('biz', 'article-details')
      formdata.append('username', this.name)
      // formdata.append('jeditor', '1')
      uploadMarkDownImg(this.url.upload, formdata).then(res => {
        insertFn(res.message)
      })
    },
    onChange() {
      // console.log('onChange', this.editor.getHtml()) // onChange 时获取编辑器最新内容
      this.$emit('onChange', this.editor.getHtml(), this.editor.getText())
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>

<style scoped>

</style>
<style src="@wangeditor/editor/dist/css/style.css"/>
